﻿using litsdk;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace litssh
{
    [litsdk.ActivityInfo(Name = "SSH命令行", RefFile = "Renci.SshNet.dll", IsLinux = true, IsFront = false, IsWinForm = false)]
    public class SSHCmdActivity : litsdk.ProcessActivity
    {
        public override string Name { get; set; } = "SSH命令行";

        public override ActivityGroup Group => ActivityGroup.NetWork;

        public string Host = "";

        public string Port = "";

        public string UserName = "";

        public string Password = "";

        public string CmdStr = "";

        public string SaveVarName = "";


        /// <summary>
        /// https://blog.csdn.net/weixin_30580943/article/details/99622989
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(ActivityContext context)
        {
            string host = context.ReplaceVar(this.Host);
            string port = context.ReplaceVar(this.Port);
            string username = context.ReplaceVar(this.UserName);
            string password = context.ReplaceVar(this.Password);
            string cmdstr = context.ReplaceVar(this.CmdStr);

            int iport = 0;
            if (!int.TryParse(port, out iport)) throw new Exception("端口号错误请检查：" + port);

            using (var sshClient = new SshClient(host, iport, username, password))
            {
                sshClient.Connect();
                using (var cmd = sshClient.CreateCommand(cmdstr))
                {
                    var res = cmd.Execute();
                    if (!string.IsNullOrEmpty(this.SaveVarName)) context.SetVarStr(this.SaveVarName, res);
                    context.WriteLog($"成功执行命令 {cmdstr} 结果 {res}");
                }
            }
        }

        public override void ShowConfig()
        {
            litsdk.API.ShowSystemConfigForm(this);
        }

        public override void Validate(ActivityContext context)
        {
            if (string.IsNullOrEmpty(this.Host)) throw new Exception("主机地址不能为空");
            if (string.IsNullOrEmpty(this.Port)) throw new Exception("端口不能为空");
            if (string.IsNullOrEmpty(this.UserName)) throw new Exception("用户名不能为空");
            if (string.IsNullOrEmpty(this.Password)) throw new Exception("密码不能为空");
            if (string.IsNullOrEmpty(this.CmdStr)) throw new Exception("命令行不能为空");
            if (!string.IsNullOrEmpty(this.SaveVarName) && !context.ContainsStr(this.SaveVarName)) throw new Exception("保存字符串不能为空");
        }
    }
}